<?php
/*******************************************************
 所有后台功能都需要加载该模块功能  单机模式
 *******************************************************/
namespace src\logic;
use \classlib\acl;
use classlib\input;
use \classlib\core as C;
class Cadmin {
	//系统创建流程的账号，专用
	const CREATEOR_USERID    = 4490;
	//主播薪资审核单据
	const WORKFLOW_SALARY_ID = 29;
	const WORKFLOW_DEPOSIT_ID=30;
	
	/**
	 * 验证权限之后的模块名称
	 * @var string
	 * @staticvar
	 */
	static $name;

	/**
	 * 超级管理员的id配置
	 * @var int
	 */
	static $super = 1;

	/**
	 * 校验用户模块操作执行权限
	 * @param view_abstract $view
	 * @param string $attachurl
	 */
	public static function chkaccess($view, $attachurl='') {
		$userid = self::islogin($view);
		if (!$attachurl) {
			$attachurl = C\router::$uri;
		}
		$where  = array('status'=>1, array('action', '%'.$attachurl.'%', \classlib\orm::OP_LIKE));
		$item   = C\model::load('main.sys.module')->get_item($where);
		//不存在或者默认模块都当做有权限了
		if ($item && $item['isdefault'] != 1 && !self::hadaccess($userid, $item['id'])) {
			$lang = C\lang::inst('adm');
			if (input::post('re') == 'extjs') {
				$view->assign_error(20001, $lang->txt('index', 20001));
			} elseif (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
				$view->assign_error(20001, $lang->txt('index', 20001));
			} else {
				C\redirect('/admin.html');
			}
		}
		//设置模块的title信息
		if ($item) {
			$lng = C\lang::lng();
			self::$name = (substr($lng, 0, 2) == 'zh')? $item['title']:$item['title_en'];
		}
		return $userid;
	}
	
	/**
	 * 验证用户是否拥有指定url的请求权限
	 * @param unknown $userid
	 * @param unknown $uri
	 * @return boolean
	 */
	public static function url_access($userid, $uri) {
		$uri    = trim($uri, '/');
		$index  = strrpos($uri, '.');
		if ($index !== false) {
			$uri= substr($uri, 0, $index);
		}
		$where  = array('status'=>1, array('action', '%'.$uri.'%', \classlib\orm::OP_LIKE));
		$item   = C\model::load('main.sys.module')->get_item($where);
		if (!$item || $item['isdefault'] == 1) {
			return true;
		}
		return self::hadaccess($userid, $item['id']);
	}
	
	/**
	 * 将需要记录日志的信息直接记录到dblog当中
	 * @param string $msg
	 * @param number $lv
	 */
	public static function log2db($msg, $lv=3) {
		$user = self::operator();
		$log  = array('type'=>$lv, 'path'=>$_SERVER['REQUEST_URI'], 
			'user'=>$user, 'msg'=>$msg, 'ip'=>C\get_ip(), 'stime'=>C\config::$nowtime);
		C\model::load('main.sys.syslog')->set_ymd()->new_one($log);
	}
	
	//获取操作者资料信息
	public static function operator() {
		$user = acl::inst()->user;
		if ($user) {
			$user = $user['nick'].'['.$user['account'].']';
		} else {
			$user = '[匿名]';
		}
		return $user;
	}
	
	/**
	 * 附加贡献的资料信息
	 * @param unknown $view
	 */
	public static function share_index($view) {
		$acl   = acl::inst();
		$zones = lconfig::ddarr('system_zone');
		$slang = lconfig::ddarr('system_lang');
		$clng  = input::cookie(C\lang::$mark);
		$nick  = $acl->user['nick'].'['.$acl->user['account'].']';
		foreach ($slang as $item) {
			if ($item[0] == $clng) {
				$clng = $item[1];
				$nick.= '@'.$clng;
				break;
			}
		}
		$tz    = input::cookie('tz');
		if (!$tz) {
			$config = C\config::load('config', false);
			$tz     = $config['datezone'];
		}
		$static= lconfig::ddarr('system_staticuri');
		$nick .= '@'.$tz;
		$lang  = C\lang::inst('adm');
		$index = $lang->get('index');
		$view->assign_by_ref('zones', $zones);
		$view->assign_by_ref('slang', $slang);
		$view->assign_by_ref('lang', $index);
		$view->assign('js', $lang->get('js'));
		$view->assign_by_ref('nick', $nick);
		$view->assign_by_ref('user', $acl->user);
		$view->assign_by_ref('staticuri', $static[0][1]);
		return $acl->user['id'];
	}
	
	/**
	 * 返回记录的多少，列表专用
	 */
	public static function offset() {
		$start = (int)input::get_post('start');
		if ($start < 0) {
			$start = 0;
		}
		$limit = (int)input::get_post('limit');
		if ($limit > 200) {
			$limit = 200;
		}
		$sort  = input::get_post('sort');
		$dir   = input::get_post('dir');
		$sorts = null;
		if ($sort && $dir) {
			$sorts = array($sort=>$dir);
		}
		return array($start, $limit, $sorts);
	}
	
	/**
	 * 检查是否有权限
	 * @param int $mid
	 * @return boolean
	 */
	public static function hadaccess($userid, $mid) {
		static $access = array();
		static $roles  = array();
		//cache住我的权限ID
		if (empty($myasid)) {
			$where = array('userid'=>$userid);
			$roles = C\model::load('main.sys.ruser')->get_column(0, -1, $where, 'ruleid');
			$where = array('userid'=>$userid);
			if ($roles) {
				$where[] = array('ruleid', $roles, \classlib\orm::OP_IN, \classlib\orm::OP_OR);
			}
			$access= C\model::load('main.sys.access')->get_column(0, -1, $where, 'menuid');
		}
		if (!in_array(self::$super, $roles) && !in_array($mid, $access)) {
			return false;
		}
		return true;
	}
	
	/**
	 * 获取权限资料列表
	 * @param array $roles
	 * @param array $access
	 * @param array $pid
	 */
	public static function get_modules($roles, $access, $pid=0) {
		$clng   = input::cookie(C\lang::$mark);
		$title  = 'title_'.$clng;
		$fields = C\model::load('main.sys.module')->get_fields();
		$title  = (isset($fields[$title]))? $title.' as title':'title';
		$fields = sprintf('id,pid,%s,memo,icon,action as url', $title);
		$where  = array(array('ishow', 1), array('`status`', 1), 
			array('pid', $pid, is_array($pid)? \classlib\orm::OP_IN:\classlib\orm::OP_EQ));
		if (!in_array(self::$super, $roles)) {//不属于超级管理员组
			$where[] = array('(');
			$where[] = array('isdefault', 1);
			$where[] = array('id', empty($access)? array(0):$access, \classlib\orm::OP_IN, \classlib\orm::OP_OR);
			$where[] = array(')');
 		}
		$sort   = array('pid'=>\classlib\orm::DESC, '`order`'=>\classlib\orm::DESC);
		$list   = C\model::load('main.sys.module')->get_list(0, -1, $where, $fields, $sort);
		return $list;
	}
	
	/**
	 * 获取用户的权限和所属组信息
	 * @param int $userid
	 * @return array
	 */
	public static function get_role_access($userid, $onlyuser=false) {
		$access   = array('roles'=>array(), 'access'=>array());
		$where    = array('userid'=>$userid);
		$access['roles'] = C\model::load('main.sys.ruser')->get_column(0, -1, $where, 'ruleid');
		if ($access['roles'] && !$onlyuser) {
			$where[] = array('ruleid', $access['roles'], \classlib\orm::OP_IN, \classlib\orm::OP_OR);
		}
		$access['access']   = C\model::load('main.sys.access')->get_column(0, -1, $where, 'menuid');
		return $access;
	}
	
	/**
	 * 清掉用户的模块权限信息
	 * @param unknown $userid
	 */
	public static function remove_access($userid) {
		C\model::load('main.sys.ruser')->get_orm()->where('userid', $userid)->delete();
		C\model::load('main.sys.ruser')->set_ver();
		C\model::load('main.sys.access')->get_orm()->where('userid', $userid)->delete();
		C\model::load('main.sys.access')->set_ver();
	}
	
	/**
	 * 新增用户权限资料信息
	 * @param int   $userid
	 * @param array $roles
	 * @param array $access
	 */
	public static function add_user_access($userid, $roles, $access) {
		//添加用户隶属权限组
		$rorm = C\model::load('main.sys.role');
		if(!empty($roles) && is_array($roles)) {
			$roles = array_unique($roles);
			foreach ($roles as $ruleid) {
				$role = $rorm->get_one($ruleid);
				if (!$role) {
					continue;
				}
				$item = array('userid'=>$userid, 'ruleid'=>$ruleid, 'agentid'=>0,
						'remark'=>'', 'stime'=>C\config::$nowtime);
				C\model::load('main.sys.ruser')->new_one($item);
			}
		}
		//新增用户个性权限
		if(!empty($access)) {
			$access = explode(',', $access);
			$access = array_unique($access);
			foreach ($access as $mid) {
				if (!is_numeric($mid) || $mid < 1) {
					continue;
				}
				$item = array('id'=>0, 'userid'=>$userid, 'ruleid'=>0, 'menuid'=>$mid);
				C\model::load('main.sys.access')->new_one($item);
			}
		}
	}
	
	/**
	 * 建立数的递归
	 * @param array $item
	 * @param array $tree
	 */
	public static function mk_tree($item, &$tree) {
		if ($item['pid'] == 0) {
			$item['leaf'] = true;
			$tree[] 	  = $item;
			return true;
		}
		foreach ($tree as &$pitem) {
			if ($pitem['id'] == $item['pid']) {
				$item['leaf']  = true;
				$pitem['children'][] = $item;
				$pitem['leaf'] = false;
				return true;
			}
			if(isset($pitem['children']) && self::mk_tree($item, $pitem['children'])) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 验证登录然后执行业务调转
	 * @param view_abstract $view
	 */
	public static function islogin($view) {
		$acl = acl::inst();
		if (!$acl->islogin()) {
			if (input::get_post('re') == 'extjs') {
				ob_end_clean();
				echo '20000';
				exit;
			} elseif (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
				$lang = C\lang::inst('adm');
				$view->assign_error(20000, $lang->txt('index', 20000));
			} else {
				C\redirect('/admin/login.html');
			}
		}
		return $acl->user['id'];
	}
	
	/**
	 * 获取工作流执行实例的地址
	 * @param int $executionid
	 * @return string 
	 */
	public static function taskurl($executeid) {
		$url = C\router::get_url('admin/workflow/executor', 'id-'.$executeid);
		return $url;
	}
	
	/**
	 * 创建一个工作流的执行实例
	 * @param int $workflowid
	 * @param string $json
	 */
	public static function build_execute($workflowid, $result, $json) {
		$worm     = C\model::load('main.proc.workflow');
		$workflow = $worm->get_one($workflowid);
		$disname  = \src\logic\workflow\doc_executor::disname(self::CREATEOR_USERID);
		$data     = array('workflowid'=>$workflow['id'], 'pid'=>0, 'overid'=>0,
			'optime'=>C\config::$nowtime, 'status'=>1, 'applyuserid'=>self::CREATEOR_USERID,
			'applyusername'=>$disname, 'stime'=>C\config::$nowtime);
		$executeid= C\model::load('main.proc.execution')->new_one($data);
		//释放首个节点信息的提交
		$where   = array('workflowid'=>$workflow['id'], 'preid'=>0);
		$node    = C\model::load('main.proc.node')->get_item($where);
		$expire  = C\config::$nowtime + $node['expire'] * 3600;
		$state   = array('workflowid'=>$workflow['id'], 'executionid'=>$executeid, 'nodeid'=>$node['id'],
			'status'=>2, 'acceptuserid'=>self::CREATEOR_USERID, 'acceptusername'=>$disname,
			'accepttime'=>C\config::$nowtime, 'createtime'=>C\config::$nowtime, 'result'=>$result,
			'lastmodify'=>C\config::$nowtime, 'expire'=>$expire, 'json'=>$json, 'remark'=>'System Build.'
		);
		C\model::load('main.proc.nodestate')->new_one($state);
		//解锁下一个结点资料信息
		$executor = new \src\logic\workflow\doc_basic();
		$executor->nextnode($state);
		return $executeid;
	}
	
	/**
	 * 获取用户的昵称资料信息
	 * @param int $userid
	 * @return string
	 */
	public static function user($userid) {
		$uorm = C\model::load('pro.pl.userinfo');
		$user = $uorm->get_one($userid);
		$user = $user['nickname'].'['.$user['email'].']-'.$user['userid'];
		return $user;
	}
	
	/**
	 * 格式化输出时间
	 * @param unknown $secs
	 * @return string
	 */
	public static function __format_times($secs) {
		$hour   = $min = $second = 0;
		$hour   = intval($secs / 3600);
		$min    = intval(($secs % 3600) / 60);
		$second =  $secs % 3600 % 60;
		return sprintf('%d H %d m %d s', $hour, $min, $second);
	}
}